
package com.snj.honeymoonresort;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.util.Log;

public class CustomHttpClient {
	/** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
    
    public static Semaphore _pore = new Semaphore(10);

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    
    public static String executeHttpPost(String $url, ArrayList<NameValuePair> postParameters) throws Exception 
    {
	  
		  String myResult = "";
		  URL url;
		  
		  Log.d("Login", "url : " + $url);
		  
			try {
				url = new URL($url);
				HttpURLConnection http = (HttpURLConnection)url.openConnection();
				http.setDefaultUseCaches(false);
				http.setDoInput(true);
				http.setDoOutput(true);
				http.setRequestMethod("POST");
				http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
				StringBuffer buffer = new StringBuffer();
				
				for(int i=0; i<postParameters.size(); i++)
				{
					if(i > 0)
					{
						buffer.append("&");
					}
					buffer.append(postParameters.get(i).getName()).append("=").append(postParameters.get(i).getValue());
				}
				
				OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "UTF-8");				
				PrintWriter writer = new PrintWriter(outStream);
				writer.write(buffer.toString());
				writer.flush();
				
				InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8");
				BufferedReader reader = new BufferedReader(tmp);
				StringBuilder builder = new StringBuilder();
				String str;
				
				while((str = reader.readLine()) != null)
				{
					builder.append(str + "\n");
				}
				
				myResult = builder.toString();
				
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch(NullPointerException e)
			{
			}
			catch(UnsupportedCharsetException e)
			{
			}
			catch(IOException e)
			{
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
			
		return myResult;
		  
	  }
    
    public static String executeHttpPostImage(String $url, ArrayList<NameValuePair> postParameters) throws Exception 
    {
	  
		  String myResult = "";
		  		  
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost($url);
				httppost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
				HttpResponse response1 = httpclient.execute(httppost);
				HttpEntity entity = response1.getEntity();

				myResult = EntityUtils.toString(entity);
				
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				Log.d("Login", "Excep : " + e.getMessage());
				e.printStackTrace();
			}
			
		return myResult;
		  
	  }
    
    
    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    synchronized public static String executeHttpGet(String url) throws Exception {
    	
    	
    	BufferedReader in = null;
        try {
            
            
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            
            
            HttpClient client = getHttpClient();
            
            HttpResponse response = client.execute(request);
            
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            
            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    synchronized public static String executeHttpGet_New(String url) throws Exception {
    	
    	
    	BufferedReader in = null;
        try {
            
            
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            
            
            HttpClient client = new DefaultHttpClient();
            
            HttpResponse response = client.execute(request);
            
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            
            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    static public Bitmap downloadBitmap(String url) 
    {
        final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        final HttpGet getRequest = new HttpGet(url);
        
        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) { 
                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
                return null;
            }
            
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent(); 
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();  
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            // Could provide a more explicit error message for IOException or IllegalStateException
            getRequest.abort();
            Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + "\n"+e.toString());
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return null;
    }
}
